<?php
namespace App;

/**
 * WebSocket客户端助手类
 * 
 * 用于在PHP代码中发送消息到WebSocket服务器
 */
class WebSocketClient
{
    /**
     * WebSocket服务器主机
     * @var string
     */
    protected $host;
    
    /**
     * WebSocket服务器端口
     * @var int
     */
    protected $port;
    
    /**
     * 构造函数
     * @param string $host
     * @param int $port
     */
    public function __construct(string $host = 'localhost', int $port = 8080)
    {
        $this->host = $host;
        $this->port = $port;
    }
    
    /**
     * 发送新订单通知
     * @param array $order 订单数据
     * @return bool
     */
    public function sendNewOrder(array $order): bool
    {
        $data = [
            'type' => 'order_new',
            'order' => $order
        ];
        
        return $this->sendMessage($data);
    }
    
    /**
     * 发送订单状态更新
     * @param array $order 订单数据
     * @return bool
     */
    public function sendOrderStatusUpdate(array $order): bool
    {
        $data = [
            'type' => 'order_status',
            'order' => $order
        ];
        
        return $this->sendMessage($data);
    }
    
    /**
     * 发送消息到WebSocket服务器
     * @param array $data
     * @return bool
     */
    public function sendMessage(array $data): bool
    {
        try {
            // 创建TCP/IP socket
            $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
            if ($socket === false) {
                return false;
            }
            
            // 设置超时
            socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, ['sec' => 2, 'usec' => 0]);
            socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, ['sec' => 2, 'usec' => 0]);
            
            // 连接服务器
            $result = socket_connect($socket, $this->host, $this->port);
            if ($result === false) {
                socket_close($socket);
                return false;
            }
            
            // 将数据转换为JSON
            $message = json_encode($data);
            
            // 发送数据
            socket_write($socket, $message, strlen($message));
            
            // 关闭socket
            socket_close($socket);
            
            return true;
        } catch (\Exception $e) {
            // 忽略错误，不影响正常业务流程
            return false;
        }
    }
} 